#include "stack.h"

void StackInit(ST* ph)
{
	assert(ph);
	ph->p = NULL;
	ph->top = 0;
	ph->capacity = 0;
}

void StackPush(ST* ph, STDatatype x)
{
	assert(ph);
	if (ph->top == ph->capacity)
	{
		int newcapacity = ph->capacity == 0 ? 4 : ph->capacity * 2;
		STDatatype* cur = (STDatatype*)realloc(ph->p, sizeof(STDatatype)*newcapacity);
		if (cur == NULL)
		{
			perror("realloc");
		}
		ph->p = cur;
		ph->capacity = newcapacity;
	}
	ph->p[ph->top] = x;
	ph->top++;
}

void StackPop(ST* ph)
{
	assert(ph);
	if (ph->top == 0)
	{
		perror("NULL");
	}
	ph->top--;
}

STDatatype StackTop(ST* ph)
{
	assert(ph);
	if (ph->top == 0)
	{
		return NULL;
	}
	return ph->p[ph->top-1];
}

void StackSize(ST* ph)
{
	assert(ph);
	printf("%d\n", ph->top);
}

void StackDestroy(ST* ph)
{
	assert(ph);
	free(ph->p);
	ph->p = NULL;
	ph->top = 0;
	ph->capacity = 0;
}
